# _*_ coding:utf-8 _*_
# @File  : exchange_rate.py
# @Time  : 2021-01-22 16:47
# @Author: zizle

import datetime
from fastapi import APIRouter, Body, Depends
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from typing import List
from db import FAConnection
from spiders.exchange_rate import ExchangeRateSpider
from interfaces.depends import verify_date, admin_logged_require
from status import r_status


exchange_rate_api = APIRouter()


@exchange_rate_api.get('/', summary='获取指定日期汇率数据')
async def get_exchange_rate(date: datetime.datetime = Depends(verify_date)):
    # 查询本数据库
    sql = 'SELECT id,rate_ts,rate_name,rate FROM dat_exchange_rate WHERE rate_ts=%s;'
    db = FAConnection(conn_name='查询汇率数据')
    records = db.query(sql, [int(date.timestamp())])
    saved = True
    if len(records) < 1:
        # 没有数据再使用爬虫爬取
        spider = ExchangeRateSpider()
        rate_data = spider.spider_exchange_rate(query_date=date.strftime('%Y-%m-%d'))
        saved = False
    else:
        rate_data = records
    # 返回数据
    # 将汇率转为float
    for item in rate_data:
        item['rate'] = float(str(item['rate']).strip())
        item['rate_name'] = item['rate_name'].strip()
        if saved:  # 数据库查出的数据增加日期列
            item['rate_date'] = datetime.datetime.fromtimestamp(item['rate_ts']).strftime('%Y-%m-%d')
    return {'code': r_status.SUCCESS, 'message': '获取数据成功!', 'saved': saved, 'data': rate_data}


@exchange_rate_api.get('/latest/', summary='获取最新日期汇率')
async def get_latest_exchange_rate():
    sql = 'SELECT id,rate_ts,rate_name,rate FROM dat_exchange_rate ' \
          'WHERE rate_ts=(SELECT MAX(rate_ts) FROM dat_exchange_rate);'
    db = FAConnection(conn_name='最新日期汇率')
    records = db.query(sql)
    # 将汇率转为float
    for item in records:
        item['rate_date'] = datetime.datetime.fromtimestamp(item['rate_ts']).strftime('%Y-%m-%d')
    return {'code': r_status.SUCCESS, 'message': '获取数据成功!', 'data': records}


class RateItem(BaseModel):
    rate_date: str
    rate_name: str
    rate: float


@exchange_rate_api.post('/', summary='保存汇率数据')
async def save_exchange_rate(person: dict = Depends(admin_logged_require), rate_data: List[RateItem] = Body(...)):
    # 转为json,处理数据
    rate_data = jsonable_encoder(rate_data)
    for item in rate_data:
        item['rate_ts'] = int(datetime.datetime.strptime(item['rate_date'], '%Y-%m-%d').timestamp())
        item['creator'] = person['uid']
        del item['rate_date']
    # 保存数据
    save_sql = 'INSERT IGNORE INTO dat_exchange_rate (creator,rate_ts,rate_name,rate) ' \
               'VALUES (%(creator)s,%(rate_ts)s,%(rate_name)s,%(rate)s);'
    db = FAConnection(conn_name='保存汇率数据')
    count, _ = db.insert(save_sql, param=rate_data, many=True)
    return {'code': r_status.CREATED_SUCCESS, 'message': f'保存成功,数量{count}'}
